package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utila.SMSUtils;
import com.itheima.reggie.utila.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){

        String phone =  user.getPhone();
        if (StringUtils.isNotBlank(phone)){
           String code =  ValidateCodeUtils.generateValidateCode(4).toString();
           log.info("短信验证码为：{}",code);
//            SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",phone,code);
            //将生成的验证码缓存到redis中，并设置有效期为5分钟
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
         //   session.setAttribute(phone,code);
            return R.success("短信验证码发送成功");
        }
        return R.error("失败");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map request, HttpSession session){

        String phone = request.get("phone").toString();
        String code = request.get("code").toString();

        //String codeInSession = session.getAttribute(phone).toString();
        //从redis中获取缓存的验证码
        Object codeInSession =  redisTemplate.opsForValue().get(phone);
        if (codeInSession!=null && codeInSession.equals(code)){
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);

            User user = userService.getOne(queryWrapper);
            if (user ==null){
                user = new User();
                user.setPhone(phone);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            //如果用户登陆成功，删除缓存中的验证码
            redisTemplate.delete(phone);
            return R.success(user);
        }
            return R.error("验证失败");
    }
}
